package br.com.salaodebeleza.domain.converter;

import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;

import br.com.salaodebeleza.domain.TbFuncionario;
import br.com.salaodebeleza.view.TbCalcularServicoMB;

@FacesConverter(value = "tbFuncionarioConverter")
public class TbFuncionarioConverter implements Converter {

	public String getAsString(
			FacesContext arg0, UIComponent arg1, Object arg2) {
		if (arg0 == null){throw new NullPointerException("context");}
		if (arg1 == null){throw new NullPointerException("component");}
		return ((TbFuncionario)arg2).getId() + "";
	}
	public Object getAsObject(
			FacesContext arg0, UIComponent arg1, String arg2) {
		if (arg0 == null){throw new NullPointerException("context");}
		if (arg1 == null){throw new NullPointerException("component");}
		FacesContext ctx = FacesContext.getCurrentInstance();
		ValueExpression vex =
				ctx.getApplication().getExpressionFactory()
				.createValueExpression(ctx.getELContext(),
						"#{tbCalcularServicoMB}",TbCalcularServicoMB.class);
		TbCalcularServicoMB tbCalcularServico = (TbCalcularServicoMB)vex.getValue(ctx.getELContext());
		TbFuncionario tbFuncionario = null;
		try {
			for(SelectItem i : tbCalcularServico.getTbFuncionarios()){
				if( (((TbFuncionario)i.getValue()).getId() + "").equals(arg2) ){
					tbFuncionario = (TbFuncionario) i.getValue();
				}
			}
		} catch( NumberFormatException e ) {
			FacesMessage message =
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Unknown value", "This is not a car number!" );
			throw new ConverterException( message );
		}
		if( tbFuncionario == null ) {
			FacesMessage message = new FacesMessage(
					FacesMessage.SEVERITY_ERROR,
					"Unknown value", "The grupo is unknown!" );
			throw new ConverterException( message );
		}
		return tbFuncionario;
	}

}
